package com.yupi.mybi.bimq;


import com.alibaba.excel.util.StringUtils;
import com.rabbitmq.client.Channel;
import com.yupi.mybi.common.AEnum;
import com.yupi.mybi.common.ErrorCode;
import com.yupi.mybi.constant.MqConstant;
import com.yupi.mybi.exception.BusinessException;
import com.yupi.mybi.exception.ThrowUtils;
import com.yupi.mybi.manager.AIManager;
import com.yupi.mybi.model.entity.Chart;
import com.yupi.mybi.service.ChartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;


@Component
@Slf4j
public class BiMessageConsumerTest {

    @Autowired
    private ChartService chartService;
    @Autowired
    private AIManager aiManager;

//    Map<String, Object> args2 = new HashMap<>();
//    //将要创建的队列绑定到指定的交换机，设置死信队列的参数
//    args2.put("x-dead-letter-exchange", DLX_EXCHANGE_NAME);
//    args2.put("x-dead-letter-routing-key", "other");

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = BiConstant.WORK_ROUTINGKEY,
                    arguments = {
                            @Argument(value = "x-dead-letter-exchange", name = BiConstant.DLX_EXCHANGE),
                            // 设置死信路由键
                            @Argument(value = "x-dead-letter-routing-key", name = BiConstant.DLX_ROUTINGKEY)
                    }),
                    exchange = @Exchange(value = BiConstant.WORK_EXCHANGE,durable = "true",type = "direct"),
            key = BiConstant.WORK_ROUTINGKEY
    ))
    public void receiveMessage(String message, Channel channel,@Header(AmqpHeaders.DELIVERY_TAG)Long deliveryTag) throws Exception {

        log.info("receiveMessage message = {}", message);
        if (StringUtils.isBlank(message)) {
            // 如果失败，消息拒绝
            channel.basicNack(deliveryTag, false, false);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "消息为空");
        }

        long chartId = Long.parseLong(message);
        Chart chart = chartService.getById(chartId);
        if (chart == null) {
            channel.basicNack(deliveryTag, false, false);
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "图表为空");
        }
        // 先修改图表任务状态为 “执行中”。等执行成功后，修改为 “已完成”、保存执行结果；执行失败后，状态修改为 “失败”，记录任务失败信息。
        chart.setId(chart.getId());
        chart.setStatus("running");
        boolean b = chartService.updateById(chart);
        if (!b) {
            channel.basicNack(deliveryTag, false, false);
            handleChartUpdateError(chart.getId(), "更新图表执行中状态失败");
            return;
        }

        //调用ai接口
        String result = aiManager.sendMsgToXingHuo(true,getUserInput(chart));
        log.info("Ai生成的数据：{}", result);
//        if(1 == 1){
//            log.info("消息发送失败---------");
//            throw new RuntimeException("演示死信队列场景");
//        }
        String[] split = result.split("'&&&&&'");
        ThrowUtils.throwIf(split.length < 1,ErrorCode.SYSTEM_ERROR,"AI生成错误");

        String genChart = split[0].trim();
        String genResult = split[1].trim();

        chart.setGenChart(genChart);
        chart.setGenResult(genResult);
        boolean flag = chartService.updateById(chart);

        chart.setStatus(String.valueOf(AEnum.SUCCEED));
        boolean updateResult = chartService.updateById(chart);
        if (!updateResult) {
            channel.basicNack(deliveryTag, false, false);
            handleChartUpdateError(chart.getId(), "更新图表成功状态失败");
        }
        // 消息确认
        channel.basicAck(deliveryTag, false);

    }

    private void handleChartUpdateError(long chartId, String execMessage) {
        Chart chart = new Chart();
        chart.setId(chartId);
        chart.setStatus("failed");
        chart.setExecMessage(execMessage);
        boolean updateResult = chartService.updateById(chart);
        if (!updateResult) {
            log.error("更新图表失败状态失败" + chartId + "," + execMessage);
        }
    }

    /**
     * 构建用户输入
     * @param chart
     * @return
     */
    public String getUserInput(Chart chart) {
        String goal = chart.getGoal();
        String chartType = chart.getChartType();
        String csvData = chart.getChartData();

        //      用户输入
        StringBuilder userInput = new StringBuilder();
        userInput.append("分析需求：").append("\n");
        String userGoal = goal;
        if (org.apache.commons.lang3.StringUtils.isNotBlank(userGoal)) {
            userGoal += "，请使用" + chartType;
        }
        userInput.append(userGoal).append("\n");
        userInput.append("原始数据:").append("\n");
        // 压缩后的数据
        userInput.append("数据：").append(csvData).append("\n");

        return userInput.toString();
    }
}
